<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>傻逼平昆</title>
</head>

<body>
	<div>
		<form data-id="login_form" action="#">
			<p>请求地址</p>
			<input name="login_host" type="text" value="http://140.143.122.74:8081/login/check" />
			<p>账号</p>
			<input name="user_name" type="text" value="pk" />
			<p>密码</p>
			<input name="user_pwd" type="text" value="123" />
			<hr>
			<input data-id="login" type="button" value="测试登录" />
		</form>
	</div>

	<script>
		const login = document.querySelector('[data-id="login"]');
		const form = document.querySelector('[data-id="login_form"]');

		login.addEventListener('click', async () => {
			const login_host = form.login_host.value;
			const username = form.user_name.value;
			const userpass = form.user_pwd.value;
			if (!login_host) {
				alert('请输入登录地地址');
				return;
			}
			if (!username) {
				alert('请输入用户名');
				return;
			}
			if (!userpass) {
				alert('请输入密码');
				return;
			}
			const data = {
				username,
				password: userpass
			};
			console.log(data);

			const postData = Object.keys(data).reduce((p, c, i) => {
				if (i === Object.keys(data).length - 1) {
					p += c + '=' + data[c];
				} else {
					p += c + '=' + data[c] + '&';
				}
				return p;
			}, '');
			console.log(postData);
			const res = await ajax('post', login_host, postData);
			console.log(res);
		});

		function ajax(method, url, data) {
			return new Promise((resolve, reject) => {
				const ajax = new XMLHttpRequest();
				ajax.open(method, url, true);
				if (method === 'get') {
					ajax.send();
				} else {
					// ajax.setRequestHeader("Content-type", "application/json");
					ajax.setRequestHeader('content-type', 'application/x-www-form-urlencoded;charset=utf-8');
					ajax.send(data);
				}
				ajax.onreadystatechange = function () {
					if (ajax.readyState == 4) {
						if ((ajax.status >= 200 && ajax.status < 300) || ajax.status == 304) {
							resolve(this.responseText);
						} else {
							reject(this.responseText);
						}
					}
				}
			});
		}
	</script>
</body>

</html>